<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="keyWord" placeholder="部门编号或名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDepts">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="180" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" :formatter="formatSex" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面
        :visible.sync用来控制弹框
    -->


    <!--新增界面-->
    <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="部门编号" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="sn">
          <el-input v-model="addForm.sn"  auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="0">启用</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <el-select v-model="addForm.manager" value-key="id" placeholder="请选择">
            <!--
            :key="item   表示唯一
            :label="item   表示选择后显示在框里面的值
            :value="item.   选择后要返回给模型的值  对象配合value-key="id"使用
            -->
            <el-option
                v-for="item in managers"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门">
          <el-cascader v-model="addForm.parent"
                       :options="tree"
                       :props="{ checkStrictly: true,
                        value : 'id',
                        label : 'name'
                      }"
                       clearable>

          </el-cascader>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

export default {
  data() {
    return {
      filters: {
        name: ''
      },
      tree:[],
      managers:[],
      title:'',
      keyWord: '',
      depts: [],
      total: 0,
      currentPage: 1,
      pageSize:10,
      listLoading: false,
      sels: [],//列表选中列


      //编辑界面数据

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ]
      },
      //新增界面数据
      addForm: {
        id: null,
        sn: '',
        name: '',
        state: -1,
        manager: null,
        parent: null
      }

    }
  },
  methods: {
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    //修改currentPage
    handleCurrentChange(val) {
      this.currentPage = val;
      console.log(this.currentPage)
      this.getDepts();
    },
    //获取部门列表
    getDepts() {
      //构造参数
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyWord:this.keyWord,
      };
      this.listLoading = true;//忙等

      this.$http.post("/dept",para)
          .then(result=>{
            this.listLoading = false;//关闭忙等
            this.depts = result.data.pagelist
            this.total = result.data.total
          }).catch(result=>{
        this.listLoading = false;//关闭忙等

      })
    },
    getEmployee(){
      this.$http.get("/emp")
          .then(result=>{
            this.managers = result.data

          }).catch(result=>{

      })
    },
    getTree(){
      this.$http.get("/dept")
          .then(result=>{
            console.log(result)
        this.tree=result.data
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => { //点击确认按钮
        this.listLoading = true;//开启列表的忙等

        this.$http.delete("/dept/"+row.id)
            .then(result=>{
              console.log(result)
              if(result.data.state){
                this.$message({
                  message: result.data.message,
                  type: 'success'
                });
              }else{
                this.$message({
                  message: result.data.message,
                  type: 'error'
                });
              }
              this.listLoading = false;
              // this.currentPage = 1
              this.getDepts()//获取数据

            }).catch(result=>{
          this.listLoading = false;
        })

        //NProgress.start();
        /*removeUser(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepts();
        });*/
      }).catch(() => {//点击取消按钮

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      //this.editFormVisible = true;
      this.getTree();
      this.getEmployee();
      this.addFormVisible = true;
      this.title="编辑";
      //克隆 复制
      this.addForm = Object.assign({}, row);
      // console.log(this.addForm)

    },
    //显示新增界面
    handleAdd: function () {
      this.getTree();
      this.getEmployee();
      this.title="新增";
      this.addFormVisible = true;
      this.addForm = {
        id: null,
        sn: '',
        name: '',
        state: -1,
        manager: null,
        parent: null
      };
    },
    //编辑

    //新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            //console.log(para)

            if(para.parent){//有值
              //将数组转为对象             //获取最后一个id
              para.parent = {"id":para.parent[para.parent.length - 1]}
            }
            // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            this.$http.put("/dept",para)
                .then(result=>{
                  if(result.data.state){
                    this.$message({
                      message: result.data.message,
                      type: 'success'
                    });
                    //关闭模态框
                    this.addFormVisible=false
                  }else {
                    this.$message({
                      message: result.data.message,
                      type: 'error'
                    });
                  }
                  this.addLoading=false;
                  this.getDepts()

                }).catch(result=>{
              this.addLoading=false;
            })
            /*  addUser(para).then((res) => {
                this.addLoading = false;
                //NProgress.done();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
                this.addFormVisible = false;
                this.getDepts();
              });*/
          });
        }
      });
    },
    selsChange: function (sels) {
      //  console.log(sels)
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = { ids: ids };
        this.$http.patch("/dept",ids)
            .then(result=>{
              if(result.data.state){
                this.listLoading = false;
                this.currentPage =1;
                this.$message({
                  message:result.data.message,
                  type:'success'
                })
                this.getDepts();
              }else {
                this.$message({
                  message:result.data.message,
                  type:'error'
                })
              }
            })
        /* batchRemoveUser(para).then((res) => {
           this.listLoading = false;
           //NProgress.done();
           this.$message({
             message: '删除成功',
             type: 'success'
           });
           this.getDepts();
         });*/
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getDepts();
  }
}

</script>

<style scoped>

</style>